import React, { useCallback, useRef } from 'react';
import { View } from '@tarojs/components';
import Canvos from './canvos';
import Taro from '@tarojs/taro';
import config from '../../common/config';
// import {APP_URLS} from '@/utils/api/api_urls'
// import { upload } from '@/utils/api/httpRequest'
const upload = (path, callback) => {
  Taro.uploadFile({
    url: `${config.filePrefix}/file/file/upload`,
    filePath: path,
    name: 'file',
    header: {
      'Content-Type': 'application/x-www-form-urlencoded;text/html; charset=utf-8',
      Authorization: Taro.getStorageSync('token'),
      Client: '04',
    },
    success(res) {
      try {
        const data = JSON.parse(res.data);
        if (data.success) {
          callback(data);
        } else {
          callback(false);
          Taro.showToast({
            title: '操作失败',
            icon: 'none',
          });
        }
      } catch (e) {
        callback(false);
      }
    },
    fail: res => {
      Taro.showToast({
        title: res.errMsg.split(' ')[1],
        icon: 'none',
      });
      callback(false);
    },
    complete() {
      // Taro.hideLoading();
    },
  });
};
const Index = (props)=>{
  const { onChange } = props;
  const CanvosRef = useRef(null);

  // 重新绘制签名
  const clearDraw = useCallback(()=>{
    CanvosRef.current.clearDraw();
  },[]);

  // 生成签名
  const createImg = useCallback(()=>{
    CanvosRef.current.createImg((res)=>{
      // console.log(res.tempFilePath);
      upload(res.tempFilePath, (data) =>{
        if (data.success) {
          onChange(data.models[0].id,data.models[0].code);
        }
      })
    });
  },[]);

  return (
    <View className='signature'>
      <Canvos ref={CanvosRef} />
      <View className='layout-flex buttons'>
        <View className='btn-warp'>
          <View onClick={clearDraw}>重新签名</View>
          <View className='text2' onClick={createImg}>确认签名</View>
        </View>
      </View>
    </View>
  );
}
export default React.memo(Index);
